<?php
	
	function SociableBeforeFilterHook($controller)
	{
		if($controller->name == 'Migration')
		{
			return;
		}
		App::import("Vendor","Sociable.FacebookApi");
		App::import("Vendor","Sociable.SociableListener");
		Configure::registerConfigModelLoder("FacebookConfig",'Sociable.FacebookConfig');
		$listner = new SociableListener();
		EventManager::addListener($listner,'*');
		$controller->helpers[] = "Sociable.Facebook";
		if(!isset($controller->params['admin']) && !$controller->Session->read("Auth.User"))
		{
			Configure::write("Facebook.noSelfInit",false);
		}else
		{
			Configure::write("Facebook.noSelfInit",true);
		}
	}
	
	function SociableBeforeLoginHook(CmsUsersController $controller)
	{
		$UserModel =  cri("Sociable.FacebookConfig")->getUserModel();
		if($UserModel->alias == $controller->_getUserModel()->alias && isset($controller->params['named']['fbLogin']) && $controller->params['named']['fbLogin']== 1)
		{
			$fbUser = FacebookApi::getInstance()->getUser();
			//if fb user logged in
			if($fbUser)
			{
				$FacebookUserModel = cri("Sociable.FacebookUser");
				if($FacebookUserModel->isUserRegistered($fbUser))
				{
					$userId = $FacebookUserModel->getFacebookUserId($fbUser);
					$userEmail = $UserModel->field("email",array("id"=>$userId));
					$password = $FacebookUserModel->getPassword($fbUser);
					$fbId = $FacebookUserModel->field("id",array("user_id"=>$userId));
					if($fbId)
					{
						$FacebookUserModel->id = $fbId;
						$FacebookUserModel->saveField('access_token',FacebookApi::getInstance()->getAccessToken());
					}
					$controller->data[$UserModel->alias] = array("email"=>$userEmail,'password'=>$password);
					if(strpos($controller->referer(),"facebook_users")!==false)
 					{
 						$controller->Session->write("Auth.redirect","/");
 					}
				}else
				{
					$url = '/'.$controller->params['url']['url'];
					$url = base64_encode($url);
					$controller->redirect(array("controller"=>"facebook_users","plugin"=>"sociable","action"=>"register",'back'=>$url));
				}
			}
		}
	}
?>